import React, { useEffect, useState } from 'react';
import { Card, Button, Typography, Spin, Table, List, message } from 'antd';
import { FileTextOutlined, DownloadOutlined } from '@ant-design/icons';
import axios from 'axios';
import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';
import './AI-Report.scss';

const { Title, Paragraph } = Typography;

const AIReport = () => {
  const [loading, setLoading] = useState(false);
  const [reportData, setReportData] = useState(null);
  const [marketData, setMarketData] = useState([]); // 假设你有一个API来获取市场数据

  // 请求投资建议

  const handleGenerate = async () => {
    setLoading(true);
    try {
      console.log(localStorage.getItem('factors'));
       if(!localStorage.getItem('factors') || localStorage.getItem('factors') === '[]') {
            message.warning('请先进行因子挖掘，才能生成投资建议');
            return;
          }
      // 发送请求到后端生成投资建议
       
      console.log("请求投资建议，因子数据：", localStorage.getItem('factors'));
      console.log("请求投资建议，市场数据：", localStorage.getItem('market_data') || marketData);
      const factors = localStorage.getItem('factors') ? JSON.parse(localStorage.getItem('factors')) : [];
      const marketDataPayload = localStorage.getItem('market_data') ? JSON.parse(localStorage.getItem('market_data')) : marketData;

      const response = await axios.post(
        '/api/data/advice',
        {
          factors,
          market_data: marketDataPayload,
        },
        {
          headers: {
        'Authorization': `Bearer ${localStorage.getItem('jwt_token')}`,
          },
        }
      );
      setReportData(response.data.data);
      message.success('投资建议生成成功');
    } catch (error) {
      console.error("生成投资建议失败:", error);
      message.error('生成投资建议失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  // 导出为 PDF
  const exportPDF = () => {
    const report = document.getElementById('ai-report-content');
    html2canvas(report).then((canvas) => {
      const imgData = canvas.toDataURL('image/png');
      const pdf = new jsPDF();
      pdf.addImage(imgData, 'PNG', 10, 10, 190, 0);
      pdf.save('ai_investment_report.pdf');
    });
  };

  const recommendationColumns = [
    { title: '分配比例', dataIndex: 'allocation', key: 'allocation' },
    { title: '产品代码', dataIndex: 'product_code', key: 'product_code' },
    { title: '产品名称', dataIndex: 'product_name', key: 'product_name' },
    { title: '推荐理由', dataIndex: 'reason', key: 'reason' },
    { title: '建议数量', dataIndex: 'suggested_quantity', key: 'suggested_quantity' },
  ];

  return (
    <div className="ai-report-page">
      <Title level={2}><FileTextOutlined /> 智能投资报告生成器</Title>
      <Paragraph type="secondary">基于因子分析的智能推荐，提供量化股票建议与个性化研报</Paragraph>

      <Button type="primary" onClick={handleGenerate} disabled={loading} style={{ marginBottom: 20 }}>
        {loading ? <Spin size="small" /> : '📊 生成投资报告'}
      </Button>

      {reportData && (
        <div id="ai-report-content" className="report-content">
          <section>
            <Title level={4}>📌 投资组合建议</Title>
            <Card title={reportData.asset_allocation}>
              <Table
                dataSource={reportData.recommendations.map((item, index) => ({
                  key: index,
                  ...item,
                }))}
                columns={recommendationColumns}
                pagination={false}
                bordered
              />
            </Card>
          </section>

          <section>
            <Title level={4}>📋 风险提示</Title>
            <List
              dataSource={reportData.risk_warnings}
              renderItem={(warning) => (
                <List.Item>
                  <span>⚠️ {warning}</span>
                </List.Item>
              )}
            />
          </section>

          <Button icon={<DownloadOutlined />} onClick={exportPDF} style={{ marginTop: 16 }}>
            导出为 PDF
          </Button>
        </div>
      )}
    </div>
  );
};

export default AIReport;
